package com.zh.model;

import com.zh.enums.CommonResponseCode;
import com.zh.service.ResponseCode;

import java.io.Serializable;

public final class RestResponse<T> implements Serializable {
    public static final RestResponse OK_VOID = ok((ResponseCode)null);
    public static final RestResponse OK_VOID_NO_MSG = okWithoutMsg((Object)null);
    public static final RestResponse FAIL_SERVER_ERROR;
    private static final long serialVersionUID = -2349476930L;

    private boolean success;
    private T data;

    private String code;

    private String message;

    public static <T> RestResponse<T> ok(T data) {
        RestResponse<T> resp = new RestResponse();
        resp.success = true;
        resp.data = data;
        resp.code = CommonResponseCode.Success.getCode();
        resp.message = CommonResponseCode.Success.getMessage();
        return resp;
    }

    public static <T> RestResponse<T> ok(T data, ResponseCode code) {
        RestResponse resp = ok(data);
        if (null != code) {
            resp.setMessage(code.getMessage());
        }

        return resp;
    }

    public static <T> RestResponse<T> ok(ResponseCode code) {
        return (RestResponse<T>) ok((Object)null, code);
    }

    public static <T> RestResponse<T> okWithoutMsg(T data) {
        RestResponse<T> resp = new RestResponse();
        resp.success = true;
        resp.data = data;
        resp.code = CommonResponseCode.Success.getCode();
        return resp;
    }

    public static <T> RestResponse<T> fail(ResponseCode code) {
        return fail(code.getCode(), code.getMessage());
    }

    public static <T> RestResponse<T> fail(ResponseCode code, Object... args) {
        return code.getArgs() != 0 && args != null && code.getArgs() == args.length ? fail(code.getCode(), String.format(code.getMessage(), args)) : fail(code.getCode(), code.getMessage());
    }

    public static <T> RestResponse<T> fail(String code, String message) {
        RestResponse<T> resp = new RestResponse();
        resp.success = false;
        resp.data = null;
        resp.code = code;
        resp.message = message;
        return resp;
    }


    public boolean isSuccess() {
        return this.success;
    }

    public T getData() {
        return this.data;
    }

    public String getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setData(T data) {
        this.data = data;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public RestResponse() {
    }

    static {
        FAIL_SERVER_ERROR = fail(CommonResponseCode.ServerError.getCode(), CommonResponseCode.ServerError.getMessage());
    }
}
